package com.stjb.furns.web;

import com.stjb.furns.dao.BasicDAO;
import com.stjb.furns.dao.OrderDAO;
import com.stjb.furns.entity.Cart;
import com.stjb.furns.entity.Member;
import com.stjb.furns.entity.Order;
import com.stjb.furns.service.OrderService;
import com.stjb.furns.service.impl.OrderServiceImpl;
import com.stjb.furns.utils.DataUtils;
import com.stjb.furns.utils.JDBCUtilsByDruid;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author situ
 * @version 1.0
 * @date 2025/5/30 1:21
 * @Description:
 */
public class OrderServlet extends BasicServlet {

    private OrderService orderService = new OrderServiceImpl();

    /**
     * 订单保存到Session和数据库
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void saveOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //购物车信息通过Session保存 所以通过Session得到购物车信息
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        //追到hashmap源码查看clear方法
        if (null == cart || cart.isEmpty()) {
            //购物车为空 跳转到首页
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
            return;
        }

        //获取当前登录的信息
        Member member = (Member) req.getSession().getAttribute("member");
        if (null == member) {
            //用户未登录 转发到登录页面
            req.getRequestDispatcher("/views/member/login.jsp").forward(req, resp);
            return;
        }
        //生成订单

        // String orderId = null;
        // try {
        //     orderId = orderService.saveOrder(cart, member.getId());
        //     JDBCUtilsByDruid.commit();//提交
        // } catch (Exception e) {
        //     JDBCUtilsByDruid.rollback();
        //     e.printStackTrace();
        // }
        String orderId = orderService.saveOrder(cart, member.getId());
        req.getSession().setAttribute("orderId", orderId);

        //重定向到checkout.jsp
        resp.sendRedirect(req.getContextPath() + "/views/order/checkout.jsp");
    }


    /**
     * 前端显示订单信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void show(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //根据当前登录用户的id查询订单信息
        //得到用户id
        int userId = DataUtils.parseInt(req.getParameter("userId"), 0);
        //得到订单信息
        List<Order> orders = orderService.queryOrderByUserId(userId);
        //将订单信息放入域中
        req.setAttribute("orders",orders);
        //请求转发到订单展示页面
        req.getRequestDispatcher("/views/order/order.jsp").forward(req,resp);
    }

}
